import Vue from "vue";
import VueRouter from "vue-router";
import HomeView from "../views/HomeView.vue";

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    name: "home",
    component: HomeView,
  },
  {
    path: "/about",
    name: "about",
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () =>
      import(/* webpackChunkName: "about" */ "../views/AboutView.vue"),
  },
  {
    path: "/login",
    name: "login",
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () =>
      import(/* webpackChunkName: "about" */ "../views/LoginView.vue"),
  },
  {
    path: "/review",
    name: "review",
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () =>
      import(/* webpackChunkName: "about" */ "../views/ReviewView.vue"),
  },
  {
    path: "/users",
    name: "users",
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () =>
      import(/* webpackChunkName: "about" */ "../views/UsersView.vue"),
  },
  {
    path: "/tags",
    name: "tags",
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () =>
      import(/* webpackChunkName: "about" */ "../views/TagsView.vue"),
  },
  {
    path: "/theme",
    name: "theme",
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () =>
      import(/* webpackChunkName: "about" */ "../views/ThemeView.vue"),
  },
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
});

router.beforeEach((to, from, next) => {
  let isAuthenticated = Number(localStorage.getItem("isAuthenticated"));
  console.log("isAuthenticated", isAuthenticated);

  if (to.path === "/") {
    //如果这个路径在首页home，则直接放行
    next();
  } else {
    //我们跳转到了非登录界面 还要判断是否登录
    if (to.path !== "/login" && !isAuthenticated) {
      if (to.path === "/") {
        //如果是注册界面，则放行
        next();
      } else {
        //否则跳转到登陆界面
        next({
          name: "login",
        });
      }
    } else {
      if (isAuthenticated) {
        //如果已经登录了
        if (to.path === "/login") {
          //如果在登录或注册界面
          next({
            name: "home",
          }); //直接跳转到首页
        } else {
          next();
        }
      } else {
        next(); //全部放行
      }
    }
  }
});

export default router;
